// 此模块执行所有的 Crawler 脚本的功能函数
const { startProcess, qiniuUpload } = require('../libs/utils'),
  { addSliderData } = require('../services/Slider'),
  { addAgencyInfo } = require('../services/AgencyInfo'),
  // 从原型上解构出方法....addRecomCourse
  { addRecomCourse } = require('../services/RecomCourse'),
  { addCollection } = require('../services/Collection'),
  { addTeacherData } = require('../services/Teacher'),
  { addStudentData } = require('../services/Student'),
  { addCourseTab } = require('../services/CourseTab'),
  { addCourseData } = require('../services/Course'),
  { addAboutus } = require('../services/Aboutus'),
  { qiniu } = require('../config/config'),
  { CRAWLER } = require('../config/error_config'),
  { returnInfo } = require('../libs/utils');

class Crawler {
  // 爬取slider轮播图数据
  async crawlSliderData(ctx, next) {
    // 将执行结果通过promise的形式，抛出
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'slider',
        // 拿到爬取出的数据，进行操作
        async message(data) {
          data.map(async (item) => {
            // { cid: '课程id', imgUrl: '图片地址' }
            if (item.imgUrl && !item.imgKey) {
              try {

                // 图片上传七牛云
                const imgData = await qiniuUpload({
                  url: item.imgUrl,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg', // 文件后缀名
                });

                // 获取服务器存储图片的 name
                if (imgData.key) {
                  item.imgKey = imgData.key;
                }

                // 将图片名称key上传至数据库
                // imgData.key = 2312313adfaf.jpg;
                const result = await addSliderData(item);

                if (result) {
                  console.log('Data create OK');
                } else {
                  console.log('Data create failed');
                }
              } catch (error) {
                console.log(error);
              }
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    // 路由上下文 挂载请求到的数据
    ctx.body = await retData;
  }


  // 爬取机构页面的信息数据
  async crawlAgencyInfo(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'agencyInfo',
        async message(data) {
          if (data.logoUrl && !data.logoKey) {
            try {
              const logoData = await qiniuUpload({
                url: data.logoUrl,
                bucket: qiniu.bucket.tximg.bucket_name,
                ext: '.jpg',
              });

              if (logoData.key) {
                data.logoKey = logoData.key;
              }

              const result = await addAgencyInfo(data);

              if (result) {
                console.log('Data create OK');
              } else {
                console.log('Data create failed');
              }
            } catch (error) {
              console.log(error);
            }
          }

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  async crawlAboutus(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'aboutus',
        async message(data) {
          if (data.posterUrl && !data.posterKey) {
            try {
              const posterData = await qiniuUpload({
                url: data.posterUrl,
                bucket: qiniu.bucket.tximg.bucket_name,
                ext: '.jpg',
              });

              if (posterData.key) {
                data.posterKey = posterData.key;
              }

              const result = await addAboutus(data);

              if (result) {
                console.log('Data create OK');
              } else {
                console.log('Data create failed');
              }
            } catch (error) {
              console.log(error);
            }
          }

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  // 访问路由 _> 1. 爬取推荐课程数据  2. 爬取到的图片上传到qiniu第三方托管 3. 将爬取到的数据整理，放入数据库 4. 将
  async crawlRecomCourse(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'recomCourse',
        // 获取到爬虫脚本、爬取到的数据
        async message(data) {
          data.map(async (item) => {
            try {
              if (item.posterUrl && !item.posterKey) {
                // 图片上传 七牛 方法
                const posterData = await qiniuUpload({
                  url: item.posterUrl,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                // 返回名称 url+名称 获取到资源
                if (posterData.key) {
                  item.posterKey = posterData.key;
                }
              }

              if (item.teacherImg && !item.teacherImgKey) {
                const teacherImgData = await qiniuUpload({
                  url: item.teacherImg,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                if (teacherImgData.key) {
                  item.teacherImgKey = teacherImgData.key;
                }
              }

              // serviecs/文件夹下 操作数据库添加数据的方法
              const result = await addRecomCourse(item);

              if (result) {
                console.log('Data create OK');
              } else {
                console.log('Data create failed');
              }
            } catch (error) {
              console.log(error);
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  async crawlCollection(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'collection',
        async message(data) {
          data.map(async (item) => {
            if (item.posterUrl && !item.posterKey) {
              try {
                const posterData = await qiniuUpload({
                  url: item.posterUrl,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                if (posterData.key) {
                  item.posterKey = posterData.key;
                }

                const result = await addCollection(item);

                if (result) {
                  console.log('Data create OK');
                } else {
                  console.log('Data create failed');
                }
              } catch (error) {
                console.log(error);
              }
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  async crawlTeacher(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'teacher',
        async message(data) {
          data.map(async (item) => {
            if (item.teacherImg && !item.teacherImgKey) {
              try {
                const imgData = await qiniuUpload({
                  url: item.teacherImg,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                if (imgData.key) {
                  item.teacherImgKey = imgData.key;
                }

                const result = await addTeacherData(item);

                if (result) {
                  console.log('Data create OK');
                } else {
                  console.log('Data create failed');
                }
              } catch (error) {
                console.log(error);
              }
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  // 爬取学生数据
  async crawlStudent(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'student',
        async message(data) {
          data.map(async (item) => {
            if (item.studentImg && !item.studentImgKey) {
              try {
                const imgData = await qiniuUpload({
                  url: item.studentImg,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                if (imgData.key) {
                  item.studentImgKey = imgData.key;
                }

                const result = await addStudentData(item);

                if (result) {
                  console.log('Data create OK');
                } else {
                  console.log('Data create failed');
                }
              } catch (error) {
                console.log(error);
              }
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  // 爬取课程tab切换栏数据
  async crawlCourseTab(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'courseTab',
        async message(data) {
          data.map(async (item) => {
            const result = await addCourseTab(item);

            if (result) {
              console.log('Data create OK');
            } else {
              console.log('Data create failed');
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }

  // 爬取课程数据
  async crawlCourseData(ctx, next) {
    const retData = await new Promise((resolve, reject) => {
      startProcess({
        file: 'course',
        async message(data) {
          data.map(async (item) => {
            if (item.posterUrl && !item.posterKey) {
              try {
                const posterData = await qiniuUpload({
                  url: item.posterUrl,
                  bucket: qiniu.bucket.tximg.bucket_name,
                  ext: '.jpg',
                });

                if (posterData.key) {
                  item.posterKey = posterData.key;
                }

                const result = await addCourseData(item);

                if (result) {
                  console.log('Data create OK');
                } else {
                  console.log('Data create failed');
                }
              } catch (error) {
                console.log(error);
              }
            }
          });

          resolve(returnInfo(CRAWLER.CRAWL_SUCCESS));
        },
        async exit(code) {
          ctx.body = await console.log(code);
        },
        async error(error) {
          resolve(returnInfo(CRAWLER.CRAWL_FAILED));
        },
      });
    });

    ctx.body = await retData;
  }
}


// 访问不同的路由，调用 Crawler 对象下面的不同的方法
// 给前端返回不同的值
module.exports = new Crawler();
